package com.genius.util.Utils.HTTP;

import com.genius.util.Atom.superMan;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RequestSuperMan implements superMan {

    private List<FileItem> list;

    public RequestSuperMan(HttpServletRequest request)throws FileUploadException{
        list =  this.fileFormParse(request);
    }

    public List<FileItem> getList(){
        return this.list;
    }

    private List<FileItem> fileFormParse(HttpServletRequest request)throws FileUploadException {
        if(!ServletFileUpload.isMultipartContent(request)){
            return null;
        }
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> list = upload.parseRequest(request);
        return list;
    }

    public Map<String,String> getFormFiled()throws UnsupportedEncodingException {
        Map<String,String> map = new HashMap<>();
        if(list!=null){
            for(FileItem item:list){
                if(item.isFormField()){
                    map.put(item.getFieldName(),item.getString("UTF-8"));
                }
            }
        }
        return map;
    }

    public  List<FileItem> getFileList(){
        List<FileItem> res = new ArrayList<>();
            if(list!=null) {
                for (FileItem item : list) {
                    if (!item.isFormField()) {
                        res.add(item);
                    }
                }
            }
       return res;
    }
}
